from django.utils.safestring import mark_safe
from django.forms.widgets import FileInput
from django.utils.translation import ugettext as _

# How to display image from ImageField in ModelAdmin:
# http://groups.google.com/group/django-users/browse_thread/thread/7cfbcc67f3af02b8/0fa00367ff96f8c8

class AdminImageFieldWithThumbWidget(FileInput):
    """
    For use with sorl-thumbnail (sorl-thumbnail.googlecode.com)
    while specifically using ImageWithThumbnailsField.  The thumbnail is displayed in the admin.
    Your model should contain something like this:
    
    image = ImageWithThumbnailsField(upload_to='img/portfolio', thumbnail={'size': (200, 200)})
    """
    
    def __init__(self):
        super(AdminImageFieldWithThumbWidget, self).__init__({})
    
    def render(self, name, value, attrs=None):
        output = []
        if value and hasattr(value, "url"):
            output.append('<a target="_blank" href="%s">%s</a><br />Replace: ' % (value.url, value.thumbnail_tag))
        output.append(super(AdminImageFieldWithThumbWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))
